package com.djj.nanny.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import com.djj.nanny.dto.UserPasswordUpdateDTO;
import com.djj.nanny.entity.ServiceStaff;
import com.djj.nanny.entity.User;

import com.djj.nanny.exception.ServiceException;
import com.djj.nanny.mapper.UserMapper;
import com.djj.nanny.service.FileService;
import com.djj.nanny.service.MenuService;
import com.djj.nanny.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    
    @Value("${user.defaultPassword}")
    private String DEFAULT_PWD;

    @Resource
    private PasswordEncoder bCryptPasswordEncoder;

    @Resource
    private ServiceStaffServiceImpl serviceStaffService;

    @Resource
    private FileService fileService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String STAFF_ROLE = "STAFF";
    private static final String CAPTCHA_KEY = "captcha:";

    /**
     * 获取用户详情
     */
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        return user;
    }

    /**
     * 分页查询用户列表
     */
    public Page<User> getUsersByPage(String name, String roleCode, Integer status,
            Integer currentPage, Integer size) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(User::getUsername, name);
        }
        if (StringUtils.isNotBlank(roleCode)) {
            queryWrapper.eq(User::getRoleCode, roleCode);
        }
        if (status != null) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        return userMapper.selectPage(new Page<>(currentPage, size), queryWrapper);
    }

    /**
     * 删除用户(修改删除逻辑)
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(Long id) {
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 检查是否是服务人员
        if (STAFF_ROLE.equals(user.getRoleCode())) {
            throw new ServiceException("该用户是服务人员，不能直接删除");
        }

        // 检查是否是服务人员
        ServiceStaff staff = serviceStaffService.getServiceStaffByUserId(id);
        if (staff != null) {
            throw new ServiceException("该用户是服务人员，不能直接删除");
        }

        // 执行删除
        if (userMapper.deleteById(id) <= 0) {
            throw new ServiceException("删除用户失败");
        }

        LOGGER.info("用户删除成功: {}", id);
    }

    /**
     * 批量删除用户(修改删除逻辑)
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteUsers(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 检查是否有服务人员
        for (Long id : ids) {
            User user = userMapper.selectById(id);
            if (user != null && STAFF_ROLE.equals(user.getRoleCode())) {
                throw new ServiceException("选中的用户中存在服务人员，不能删除");
            }
            ServiceStaff staff = serviceStaffService.getServiceStaffByUserId(id);
            if (staff != null) {
                throw new ServiceException("选中的用户中存在服务人员，不能删除");
            }
        }

        // 执行批量删除
        if (userMapper.deleteBatchIds(ids) <= 0) {
            throw new ServiceException("批量删除用户失败");
        }

        LOGGER.info("批量删除用户成功: count={}", ids.size());
    }

    @Override
    public User login(String username, String password, String captcha, String captchaKey) {
        // 验证验证码
        String savedCaptcha = stringRedisTemplate.opsForValue().get(CAPTCHA_KEY + captchaKey);
        if (savedCaptcha == null) {
            throw new ServiceException("验证码已过期");
        }
        if (!savedCaptcha.equals(captcha.toLowerCase())) {
            throw new ServiceException("验证码错误");
        }
        // 删除已使用的验证码
        stringRedisTemplate.delete(CAPTCHA_KEY + captchaKey);

        // 验证用户名和密码
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        if (!bCryptPasswordEncoder.matches(password, user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        return user;
    }

    public void createUser(User user) {
        // 检查用户名是否存在
        if (userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, user.getUsername())
            ) != null) {
            throw new ServiceException("用户名已存在");
        }
        
        user.setPassword(StringUtils.isNotBlank(user.getPassword()) ? user.getPassword() : DEFAULT_PWD);
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        
        if (userMapper.insert(user) <= 0) {
            throw new ServiceException("用户创建失败");
        }
    }

    /**
     * 更新用户信息(修改更新逻辑)
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user) {
        // 检查用户是否存在
        User existUser = userMapper.selectById(user.getId());
        if (existUser == null) {
            throw new ServiceException("用户不存在");
        }

        // 如果是服务人员，不允许修改角色
        if (STAFF_ROLE.equals(existUser.getRoleCode())) {
            if (!STAFF_ROLE.equals(user.getRoleCode())) {
                throw new ServiceException("服务人员用户不能修改角色");
            }
        }
        if(!ObjectUtil.equals(existUser.getAvatar(), user.getAvatar())) {
            fileService.deleteFile(existUser.getAvatar());
        }

        // 执行更新
        if (userMapper.updateById(user) <= 0) {
            throw new ServiceException("更新用户失败");
        }

        LOGGER.info("用户信息更新成功: {}", user.getId());
    }


    public void updatePassword(Long id, UserPasswordUpdateDTO update) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 验证旧密码
        if (!bCryptPasswordEncoder.matches(update.getOldPassword(), user.getPassword())) {
            throw new ServiceException("原密码错误");
        }
        
        // 更新新密码
        user.setPassword(bCryptPasswordEncoder.encode(update.getNewPassword()));
        if (userMapper.updateById(user) <= 0) {
            throw new ServiceException("密码修改失败");
        }
    }

    /**
     * 重置用户密码
     */
    public String resetPassword(Long id) {
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 重置为默认密码
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(bCryptPasswordEncoder.encode(DEFAULT_PWD));
        
        if (userMapper.updateById(updateUser) <= 0) {
            throw new ServiceException("密码重置失败");
        }
        LOGGER.info("用户密码重置成功: {}", id);
        return DEFAULT_PWD;

    }
}
